package com.zx.Ding.service.impl;/**
 * Author:JasonZ
 * Data:2023/3/17
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.Ding.entity.CategoryComment;
import com.zx.Ding.entity.CategoryDetail;
import com.zx.Ding.mapper.CategoryCommentMapper;
import com.zx.Ding.service.CategoryCommentService;
import com.zx.Ding.service.CategoryDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * @program: Ding
 *
 * @description:
 *
 * @author: JasonZ
 *
 * @create: 2023-03-17 11:50
 **/
@Service
public class CategoryCommentServiceImpl extends ServiceImpl<CategoryCommentMapper, CategoryComment> implements CategoryCommentService {

    @Autowired
    private CategoryDetailService categoryDetailService;
    @Autowired
    private CategoryCommentService categoryCommentService;
    @Override
    public void sava(CategoryComment categoryComment) {
        categoryCommentService.save(categoryComment);
        Long categoryId = categoryComment.getCategoryId();
        LambdaQueryWrapper<CategoryDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryDetail::getCategoryId,categoryId);
        //获得该评论对应的门店
        CategoryDetail categoryDetail = categoryDetailService.getOne(queryWrapper);
        //评论条数+1
        categoryDetail.setCommentTotal(categoryDetail.getCommentTotal()+1);
        //门店平均分变化
        LambdaQueryWrapper<CategoryComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategoryComment::getCategoryId,categoryId);
        List<CategoryComment> comments = categoryCommentService.list(wrapper);
        //求该门店的总分和。
        QueryWrapper<CategoryComment> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select(("IFNULL(sum(rating),0) as totalScore"))
                .eq("category_id", categoryId);
        Map<String, Object> map = this.getMap(queryWrapper1);
        BigDecimal sumCount = (BigDecimal) map.get("totalScore");
        //得到平均分
        System.out.println("------"+comments.size()+"-----"+sumCount);
        BigDecimal result = sumCount.divide(BigDecimal.valueOf(comments.size()), 2, RoundingMode.HALF_UP);
        categoryDetail.setScore(result);
        categoryDetailService.updateById(categoryDetail);
    }
}